<?
/**************************************************

*   Description:  Payment transactions maintaining

*****************************************************  */


//require_once('../inc/forms.php');
if (!isset($r)) $r = "../";
require_once($r."_config/db.php");
require_once($r."_engine/c_sql_table.php");


class objPayment  {
	var $someHTML;
	var $inputsArr;
	var $servicesArr;
	var $userID;
	var $buttonCaption;
	var $isRecurring = 1; //sets if payment will be recurring untill user cancels ordered subscription (1-true)
	var $isTrial = 1; //sets if there's a trial period (1-true)
	var $isTrialPassed = '0'; // boolean is trial passed or not
	var $trialDays;
	var $isTerms;
	var $isTrialFree;
	var $periodsArray = Array();
	var $periodsPricesArray = Array();
	
	var $PAPcode = "pap_dx8vc2s5";

    //general Info PAYPAL
	var $PayPalTestMode = false;
	var $PayPalLink = "https://www.paypal.com/cgi-bin/webscr";
	var $PayPalLink_test = "https://www.sandbox.paypal.com/cgi-bin/webscr";
	var $command = "_xclick-subscriptions";
	var $command2 = "_xclick";
	var $businessID = "ak@cid.kiev.ua"; //email assigned to account
	var $businessID_test = "derang_1258232390_biz@ukr.net"; //email assigned to account
	var $itemName; //maximum 127 characters
	var $returnURL = "http://www.intelli4x.com/index.php?p=rates&s=status&step=success"; //if payment succeeded
	var $returnURL_test = "http://test.w3monitor.com/members/signup_success.php"; //if payment succeeded
	var $notifyURL = "http://www.intelli4x.com/test_ipn.php"; //IPN
	var $notifyURL_test = "http://www.alpha.intelli4x.com/test_ipn.php"; //IPN
	var $returnBehaviour = 2; //return to return_url with POST transaction vars
	var $cancelURL = "http://www.intelli4x.com/index.php?p=rates&s=status&step=cancel"; //if payment cancelled
	var $cancelURL_test = "http://test.w3monitor.com/members/signup_success.php"; //if payment cancelled
	//payment details
	var $trialPrice = 0;
	var $trialUnits = "D"; //days
	var $trialLength = 14;
	var $cyclePrice; //charge per month
	var $cycleLength = 1;
	var $cycleUnits = "M"; //months
	var $cyclePend = 1; //recurring payments
	var $cycleTimes = 1; // times run cycle
	//other
	var $noNote = 1; //required param
	var $subscrID; //unique
	var $currency = "USD";
	var $modifyButton = 0; //allows only to create new or edit existing
	var $usrMaqnage = 0;
	
	var $globalCounter = 0;

	//WEBMONEY params
	var $webmoneySKey = "Secret Key";
	var $WebmoneyLink = array("ru" => "https://merchant.webmoney.ru/lmi/payment.asp",
						"en" => "https://merchant.wmtransfer.com/lmi/payment.asp");
	// AG webmoney
	//var $wallet = array("ru" => "U872158888616",
	//					"en" => "Z226365705003");
	//var $wallet = array("ru" => "U160811415353",
						//"en" => "Z086153001552");
	var $wallet = array("ru" => "Z086153001552",
						"en" => "Z086153001552");
	var $URLResult = "http://www.intelli4x.com/webmoney_ipn";
	var $URLSuccess = "http://www.intelli4x.com/index.php?p=rates&s=status&step=success";
	var $URLFail = "http://www.intelli4x.com/index.php?p=rates&s=status&step=fail";

	//EGOLD params
	var $EgoldLink = "https://www.e-gold.com/sci_asp/payments.asp";
	var $EgoldAccount = "5243496";
	var $EgoldResult = "http://www.intelli4x.com/egold_ipn";
	var $EgoldSuccess = "http://www.intelli4x.com/index.php?p=rates&s=status&step=success";
	var $EgoldFail = "http://www.intelli4x.com/index.php?p=rates&s=status&step=fail";

	//Google params
	//var $GoogleLink = "https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/1234567890";
	//var $GoogleLink = "https://sandbox.google.com/checkout/api/checkout/v2/checkoutForm/Merchant/458571536472896"; //test
	var $GoogleLink = "https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/174440055805867"; //real



	//var $GoogleMerchantID = "458571536472896"; //test
	var $GoogleMerchantID = "174440055805867"; //real
	//var $GoogleMerchantKey = "SCohvosxSurFGq10z5yYkg"; //test
	var $GoogleMerchantKey = "Y_NNsBxvPX5Fx4Gn2i5vhQ"; //real
	var $GoogleResult = "http://www.intelli4x.com/google_ipn.php";
	var $GoogleSuccess = "http://www.intelli4x.com/index.php?p=rates&s=status&step=success";
	var $GoogleFail = "http://www.intelli4x.com/index.php?p=rates&s=status&step=fail";

	var $WireLink = "wire-transfer.html"; //real


 		function __construct() {
			global $config;
			//$this->db = objDataBase::GetInstance();//new objDataBase();
			$this->isTrialFree = $config['trial']['free'];
			$this->trialDays = $config['trial']['days'];
			
			//if test mode for PayPal enabled
			if ($this->PayPalTestMode) {
				//$this->PayPalLink = $this->PayPalLink_test;
				//$this->businessID = $this->businessID_test;
				$this->notifyURL = $this->notifyURL_test;
				$this->cancelURL = $this->cancelURL_test;
				$this->returnURL = $this->returnURL_test;
			}
      	} //constructor


        // sends an email
      	function subscrNotify($payer_email,$userID,$subscrTime,$subscrPeriod) {
	      	$mailshot = new objMailshot();
			$mailshot->subscrNotify($payer_email,$userID,$subscrTime,$subscrPeriod,"subscr_new");
		}


      ///////////////////////////////////
      // returns complete form HTML code
      ///////////////////////////////////
      function getFormSource() {
      	$formSource = $this->startForm($this->PayPalLink,$this->someHTML,"paypalForm");
      	$formSource .= $this->setPostParams();
      	//$formSource .= $this->submitButton($this->buttonCaption,"paymentButton");
      	$formSource .= $this->endForm();

      	return $formSource;
      }

      function getWebmoneyFormSource() {
      	$formSource = $this->startForm($this->WebmoneyLink[$this->TranslationMessage->GetLang()],$this->someHTML,"webmoneyForm");
      	$formSource .= $this->setWebmoneyPostParams();
      	//$formSource .= $this->submitButton($this->buttonCaption,"paymentButton");
      	$formSource .= $this->endForm();

      	return $formSource;
      }

      function getEgoldFormSource() {
      	$formSource = $this->startForm($this->EgoldLink,$this->someHTML,"egoldForm");
      	$formSource .= $this->setEgoldPostParams();
      	//$formSource .= $this->submitButton($this->buttonCaption,"paymentButton");
      	$formSource .= $this->endForm();

      	return $formSource;
      }

      function getGoogleFormSource() {
      	$formSource = $this->startForm($this->GoogleLink,$this->someHTML,"BB_BuyButtonForm");
      	$formSource .= $this->setGooglePostParams();
      	//$formSource .= $this->submitButton($this->buttonCaption,"paymentButton");
      	$formSource .= $this->endForm();

      	return $formSource;
      }

      function getWireFormSource() {
      	$formSource = $this->startForm($this->WireLink,$this->someHTML,"wireForm");
      	$formSource .= $this->setWirePostParams();
      	//$formSource .= $this->submitButton($this->buttonCaption,"paymentButton");
      	$formSource .= $this->endForm();

      	return $formSource;
      }

      ///////////////////////////////////////////
      // set subscription params passed by user
      //////////////////////////////////////////
      function setSubscrParams($itemName,$returnURL,$cancelURL,$cyclePrice,$cycleTimes,$cycleUnits,$userID,$isRecurring,$isTrial,$subscrID) {
     	$this->isRecurring = $isRecurring;
     	if ($cycleUnits=="D") $sDays = $cycleTimes;
     	else $sDays = $this->getSubscrDays($cycleTimes);
     	//else $sDays = $cycleTimes*30;

		$this->itemName = $itemName;
		$this->returnURL = $returnURL;
		$this->cancelURL = $cancelURL;
		$this->cyclePrice = $cyclePrice;
		$this->cycleLength = $cycleTimes;
		$this->cycleUnits = $cycleUnits;
		$this->isTrial = $isTrial;
		if ($isRecurring==1) $this->cycleTimes = $cycleTimes;
		$this->subscrID = $userID."_".$sDays."_".time()."_".$cycleUnits."_".$subscrID;
		$this->subscrShortID = $userID."_".time()."_".$cycleUnits."_";
		$this->subscrDays = $sDays;

      	//return true;
      }

      function getSubscrDays($times) {
     	$cMonth = date("m",time());
     	$cDay = date("d",time());
     	$cYear = date("Y",time());
     	$cHour = date("G",time());

     	$nTime = round((mktime($cHour,0,0,$cMonth+$times,$cDay,$cYear) - time())/86400);

      	return $nTime;
      }

      //////////////////////////////////////////////////
      // forms hidden inputs set HTML to post to PayPal
      /////////////////////////////////////////////////

      function setPostParams() {
      	$postParams = $this->hiddenInput("cmd",$this->command2);
      	$postParams .= $this->hiddenInput("business",$this->businessID);
      	$postParams .= $this->hiddenInput("item_name",$this->itemName);
      	$postParams .= $this->hiddenInput("return",$this->returnURL);
		$postParams .= $this->hiddenInput("notify_url",$this->notifyURL);
      	$postParams .= $this->hiddenInput("rm",$this->returnBehaviour);
      	$postParams .= $this->hiddenInput("cancel_return",$this->cancelURL);
		$postParams .= $this->hiddenInput("no_shipping","1");
      	$postParams .= $this->hiddenInput("no_note",$this->noNote);
      	$postParams .= $this->hiddenInput("invoice",$this->subscrID);
      	$postParams .= $this->hiddenInput("amount",$this->currency);
      	$postParams .= $this->hiddenInput("currency_code",$this->currency);
		$postParams .= $this->hiddenInput("custom","",$this->PAPcode);

      	return $postParams;
      }


       function setWebmoneyPostParams() {
      	$postParams = $this->hiddenInput("LMI_PAYEE_PURSE",$this->wallet[$this->TranslationMessage->GetLang()]);
      	$postParams .= $this->hiddenInput("LMI_PAYMENT_AMOUNT","");
      	$postParams .= $this->hiddenInput("LMI_PAYMENT_NO",time());
      	$postParams .= $this->hiddenInput("LMI_PAYMENT_DESC","");
      	$postParams .= $this->hiddenInput("LMI_SIM_MODE",0);
      	$postParams .= $this->hiddenInput("invoice",$this->subscrID);
      	return $postParams;
      }


      function setEgoldPostParams() {
      	$postParams .= $this->hiddenInput("PAYEE_ACCOUNT",$this->EgoldAccount);
		$postParams .= $this->hiddenInput("PAYEE_NAME","IntelliForex - Forex Forecasts Subscription");
		$postParams .= $this->hiddenInput("PAYMENT_AMOUNT","");
		$postParams .= $this->hiddenInput("PAYMENT_UNITS","1");
		$postParams .= $this->hiddenInput("PAYMENT_METAL_ID","1");
		$postParams .= $this->hiddenInput("STATUS_URL",$this->EgoldResult);
		$postParams .= $this->hiddenInput("PAYMENT_URL",$this->EgoldSuccess);
		$postParams .= $this->hiddenInput("PAYMENT_URL_METHOD","LINK");
		$postParams .= $this->hiddenInput("NOPAYMENT_URL",$this->EgoldFail);
		$postParams .= $this->hiddenInput("NOPAYMENT_URL_METHOD","LINK");
		$postParams .= $this->hiddenInput("BAGGAGE_FIELDS","invoice");
		$postParams .= $this->hiddenInput("invoice",$this->subscrID);
		$postParams .= $this->hiddenInput("SUGGESTED_MEMO","");
      	return $postParams;
      }

      function setGooglePostParams() {
      	$postParams .= $this->hiddenInput("item_name_1",'2323');
		$postParams .= $this->hiddenInput("item_description_1","IntelliForex - Forex Forecasts Subscription");
		$postParams .= $this->hiddenInput("item_quantity_1","1");
		$postParams .= $this->hiddenInput("item_price_1","1");
		$postParams .= $this->hiddenInput("item_currency_1","USD");
		$postParams .= $this->hiddenInput("_charset_","utf-8");
		$postParams .= $this->hiddenInput("shopping-cart_items_item-1_unit-invoice",$this->subscrID);
      	return $postParams;
      }

      function setWirePostParams() {
      	$postParams .= $this->hiddenInput("item_name_1",'2323');
		$postParams .= $this->hiddenInput("item_description_1","IntelliForex - Forex Forecasts Subscription");
		$postParams .= $this->hiddenInput("subscr_length",$this->cycleLength);
		$postParams .= $this->hiddenInput("item_price_1","1");
		$postParams .= $this->hiddenInput("item_currency_1","USD");
      	return $postParams;
      }




  	public function setUser($userID) {
		$this->userID = $userID;
      	//return true;
  	}

  	public function setSubscr($isSubscribed) {
		$this->isSubscribed = $isSubscribed;
      	//return true;
  	}

  	public function setTrial($isTrialFinished) {
		$this->isTrialFinished = $isTrialFinished;
      	//return true;
  	}

  	public function getTxn() {
        global $_POST;
      	return $_POST['txn_type'];
  	}


     ///////////////////////////////////////////////////////////////////
     // process params recieved from PayPal after transaction completed
     ///////////////////////////////////////////////////////////////////
	public function setTrialInfo($timestmp) {

        $this->trialDays = intval((time() - $timestmp)/86400);

		if ((intval($this->trialLength)-intval($this->trialDays))<=0){
        	$this->isTrialPassed = '1';
  		}
  		else {
  		   $this->isTrialPassed = '0';
  		}



      	//return true;
  	}
	



  	public function getServicesData() {
        $cnter = 0;
		$sql_where = "";
		
		//if trial is free add array element
		if ($this->isTrialFree){
			$sql_where = " AND service_time_units!='D' ";
			$servicesArr[0] = array(
				'id' => 0,
				'name' => $this->TranslationMessage->GetMessage('headers__signup'),
				//'price' => '13,85',
				'price' => $this->TranslationMessage->GetMessage('_order_service__msgFree'),
				'discount' => $this->TranslationMessage->GetMessage('_order_service__msgFree'),
				'status' => 'FREE',
				'time' => $this->TranslationMessage->GetMessage('headers__signup'));
		}

	  	$recordSet = $this->db->Execute("SELECT st.*, s.Name FROM fa_subscriptions_types st ".
					" LEFT JOIN fa_systems s ON st.service_system=s.SystemID ".
					" WHERE service_active=1 ".$sql_where." ORDER BY service_time_units, service_time ");
		if ($recordSet){
			while (!$recordSet->EOF) {
				$this->itemName = $recordSet->fields['service_name'];
                $price = $recordSet->fields['service_price'];
				if ($recordSet->fields['service_discount']>0) $price = $recordSet->fields['service_discount'];
				$this->setSubscrParams($recordSet->fields['service_name'],$this->returnURL,$this->cancelURL,$price,$recordSet->fields['service_time'],$recordSet->fields['service_time_units'],$this->userID,0,0,$recordSet->fields['service_id']);

                // generate payment forms source
                if ($this->globalCounter<1){
					$this->inputsArr[] = $this->getFormSource();
					$this->inputsArr[] = $this->getWebmoneyFormSource();
					//$this->inputsArr[] = $this->getEgoldFormSource();
					//$this->inputsArr[] = $this->getGoogleFormSource();
					//$this->inputsArr[] = $this->getWireFormSource();
				}
				$this->globalCounter++;

				//
                //if ($this->TranslationMessage->GetLang()!="ru") {
                	$sPrice = $recordSet->fields['service_price'];
                	$sDiscount = $recordSet->fields['service_discount'];
                //} else {
                	//$sPrice = $recordSet->fields['service_discount_ua'];
                	//$sDiscount = $recordSet->fields['service_price_ua'];
                	//$price = $recordSet->fields['service_discount_ua'];
                //}
				
				$periodStamp = $recordSet->fields['service_time'].$recordSet->fields['service_time_units'];
				$pSystem = $recordSet->fields['service_system'];
				$this->periodsPricesArray[$pSystem][strtolower($periodStamp)] = $sPrice;
				
				if (!array_key_exists($periodStamp, $this->periodsArray)) {
					$period = array();
					$period['id'] = strtolower($recordSet->fields['service_time'].$recordSet->fields['service_time_units']);
					$period['time'] = ($recordSet->fields['service_time_units'] == "D") ? $this->trialDays : $recordSet->fields['service_time'];
					$period['time_units'] = $recordSet->fields['service_time_units'];
					$period['days'] = $this->subscrDays;
					$period['invoice'] = $this->subscrShortID;
					$this->periodsArray[$periodStamp] = $period;
				}
				
				
				$servicesArr[] = array(
					'id' => $recordSet->fields['service_id'],
					'name' => $recordSet->fields['service_name'],
					'system' => $recordSet->fields['service_system'],
					'sys_name' => $recordSet->fields['Name'],
					'sys_stamp' => $recordSet->fields['service_system']."%".$recordSet->fields['service_time'],
					'price' => $sPrice,
					'discount' => $sDiscount,
					'guarantee' => $recordSet->fields['service_guarantee'],
					'invoice' => $this->subscrID,
					'fprice' => $price);

		        $recordSet->MoveNext();
			}
		}
		
		//var_dump($this->periodsPricesArray);
		
		return $servicesArr;
  	}  // getServicesData

}



//-------------------------------------------------------------------------------------------------------
class objUserSubscription {
	public $code = false;
	protected $_user = false;
	public $userData = array();
	public $activateSubscription = 0;
	public $subscriptionStart = 0;
	public $subscriptionEnd = false;
	public $subscrStartTime;
	public $paymentCompleted = "Completed";
	public $paymentStatus = "";


    public function __construct() {
    	//$this->_DataBase = objDataBase::GetInstance();
    	//$this->_DataBase->debug = true;
        $this->_sqls();
    } //constructor
	
	

	//check if DB record for user exists
	public function checkSubscrRecordExists ($invoice) {

        $rcd = mysql_fetch_array( execute_query("SELECT count(*) as subscriptions FROM subscriptions ".
		" WHERE invoice='$invoice'") );
		
		

        if ($rcd['subscriptions']>0) {
        	return true;
        } else return false;
    }

    public function getUserInvoiceData ($invoice, $payment_status) {
		$subscrID = explode("_",$invoice);

		$this->userData['plan_id'] = $subscrID[0];
		$this->userData['account_id'] = $subscrID[1];
		$this->userData['period'] = $subscrID[2];
		$this->userData['units'] = $subscrID[3];
		$this->userData['time'] = $subscrID[4];
		$this->userData['payment'] = $payment_status;
		$this->userData['invoice'] = $invoice;

        return $this->userData;
    }
	
	public function getSubscriptionEnd ($start, $period, $units) {
		$multi = 1;
		if ($units=="W") $multi = 7;
		if ($units=="M") $multi = 30;
		if ($units=="Y") $multi = 365;
		$this->subscriptionEnd = date("Y-m-d G:i:s", ($start + 86400 * ($multi * $period)) );
		$this->subscriptionDays = $multi * $period;
        return $this->subscriptionEnd;
    }


    public function terminateUserSubscription ($userID, $subscrID, $subscrSystem) {
    	$this->_DataBase->handler->Execute($this->_querys['terminate_subscription'], array($userID, $subscrID, $subscrSystem));
        return true;
    }


    public function processSubscription () {
        if ( !$this->checkSubscrRecordExists ($this->userData['invoice']) ) {
		
			$sql = "INSERT INTO subscriptions ".
				"(invoice, account_id, date_start, date_end, date_updated, payment_status, plan_id, days, active) ".
				"VALUES('".$this->userData['invoice']."',".
				$this->userData['account_id'].",'".
				$this->subscriptionStart."','".
				$this->subscriptionEnd."',".
				"NOW(),'".
				$this->paymentStatus."',".
				$this->userData['plan_id'].",".
				$this->subscriptionDays.",".
				$this->activateSubscription.")";
	      	$recordSet = execute_query($sql);
	      	echo "<br>INSERT<br>";
       	} else {
			$sql = "UPDATE subscriptions SET ".
				"date_updated=NOW(), ".
				"payment_status='".$this->paymentStatus."', ". 
				"active=".$this->activateSubscription. 
			" WHERE invoice='".$this->userData['invoice']."'";
				
       		$recordSet = execute_query($sql);
       		echo "<br>UPDATE<br>";
       	}

  		return true; 
	}



	protected function _sqls() {

		$this->_querys['check_subscription'] = "SELECT count(*) as subscriptions FROM subscriptions ".
		" WHERE account_id=? AND invoice=? ";
		
		$this->_querys['create_subscription'] = "INSERT INTO subscriptions (invoice,  account_id, date_start, date_updated,  plan_id, active) VALUES(?,?,?,NOW(),?,?)";
		
		$this->_querys['update_subscription'] = "UPDATE subscriptions ".
		" SET subscr_end=?, date_start=?, date_updated=NOW(), active=? ". 
		" WHERE user_id=? AND subscr_id=?";

		$this->_querys['terminate_subscription'] = "UPDATE subscriptions ".
		" SET active=0 WHERE id=?"; 

	} //_sqls


} //class UserUnsubscribe



?>